package com.flycat.controller.admin;
import com.flycat.common.enumeration.StatusEnum;
import com.flycat.common.util.QueryUtils;
import com.flycat.common.util.RoleUtils;
import com.flycat.common.util.SessionUtils;
import com.flycat.common.util.TransferUtils;
import com.flycat.core.Result;
import com.flycat.core.ResultGenerator;
import com.flycat.dao.po.MerchantInfo;
import com.flycat.dao.po.SysPermission;
import com.flycat.dao.po.SysPermissionRole;
import com.flycat.dto.MenuDTO;
import com.flycat.dto.SysPermissionDTO;
import com.flycat.dto.query.SysPermissionQuery;
import com.flycat.service.SysPermissionRoleService;
import com.flycat.service.SysPermissionService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* Created by yalei.chen on 2017/10/18.
*/
@RestController
@RequestMapping("/admin/permission")
@Api(value = "权限管理",tags = "平台方-权限管理")
public class SysPermissionController {
    @Resource
    private SysPermissionService sysPermissionService;

    @Resource
    private SysPermissionRoleService sysPermissionRoleService;

    @PostMapping("/add")
    @ApiOperation(value = "添加权限资源", notes = "添加权限资源")
    public Result add(SysPermissionDTO sysPermission) {

        SysPermission permission = TransferUtils.poToDto(sysPermission, SysPermission.class);
        sysPermissionService.save(permission);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除权限资源", notes = "删除权限资源")
    public Result delete(@RequestParam Integer id) {
        sysPermissionService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新权限资源", notes = "更新权限资源")
    public Result update(SysPermissionDTO sysPermission) {

        if(Objects.isNull(sysPermission.getId())){
            return ResultGenerator.genFailResult("主键id不能为空");
        }
        SysPermission permission = TransferUtils.poToDto(sysPermission, SysPermission.class);
        sysPermissionService.update(permission);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    @ApiOperation(value = "查看权限资源详情", notes = "查看权限资源详情")
    public Result<SysPermissionDTO> detail(@RequestParam Integer id) {
        SysPermission sysPermission = sysPermissionService.findById(id);
        SysPermissionDTO permission = TransferUtils.poToDto(sysPermission, SysPermissionDTO.class);
        return ResultGenerator.genSuccessResult(permission);
    }

    @PostMapping("/list")
    @ApiOperation(value = "查看权限资源列表", notes = "查看权限资源列表")
    public Result<PageInfo<SysPermissionDTO>> list(SysPermissionQuery query) {

        Condition condition = conditionConverter(query);
        PageInfo<SysPermission> poPage = sysPermissionService.findByConditionPaged(condition, query.getPageNoReasonable(), query.getPageSizeReasonable());
        PageInfo<SysPermissionDTO> pageInfo = TransferUtils.pagePoToDto((Page) poPage.getList(), SysPermissionDTO.class);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @PostMapping("/addToRole")
    @ApiOperation(value = "为角色赋权", notes = "为角色赋权")
    public Result addToRole(@ApiParam("角色id 1:平台方 2:供应商 3:分销商") @RequestParam Integer role, @ApiParam("权限资源id") @RequestParam Integer permissionId) {
        SysPermissionRole record = new SysPermissionRole();
        record.setSysRoleId(role);
        record.setSysPermissionId(permissionId);
        sysPermissionRoleService.save(record);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/deleteToRole")
    @ApiOperation(value = "删除角色赋权", notes = "删除角色赋权")
    public Result deleteToRole(@ApiParam("角色id 1:平台方 2:供应商 3:分销商") @RequestParam Integer role, @ApiParam("权限资源id") @RequestParam Integer permissionId) {

        Condition condition = new Condition(SysPermissionRole.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("sysRoleId",role);
        criteria.andEqualTo("sysPermissionId",permissionId);
        sysPermissionRoleService.deleteByCondition(condition);
        return ResultGenerator.genSuccessResult();
    }


    @PostMapping("/getMenus")
    @ApiOperation(value = "为角色赋权", notes = "为角色赋权")
    public Result<List<MenuDTO>> getMenus(HttpSession session) {

        MerchantInfo user = (MerchantInfo) session.getAttribute(SessionUtils.STORE_SESSION_USER);

        List<SysPermission> permissions = sysPermissionService.findMenusByRole(RoleUtils.merchantType2Role(user.getType()));

        List<MenuDTO> menus = transfer2Menus(permissions);

//        menus.add(new MenuDTO("订单管理","#order",(byte)1,0,null));
//
//        ArrayList<MenuDTO> subMenus = new ArrayList<>();
//        subMenus.add(new MenuDTO("拼车产品管理","#product_pin",(byte)0,1,null));
//        subMenus.add(new MenuDTO("新建拼车产品","#product_pinAdd",(byte)0,1,null));
//        subMenus.add(new MenuDTO("拼车用车规则管理","#product_pinRule",(byte)0,1,null));
//        subMenus.add(new MenuDTO("添加拼车用车规则介绍","#product_pinRuleAdd",(byte)0,1,null));
//        subMenus.add(new MenuDTO("专车产品管理","#product_zhuan",(byte)0,1,null));
//        subMenus.add(new MenuDTO("新建专车产品","#product_zhuanAdd",(byte)0,1,null));
//        menus.add(new MenuDTO("产品管理","#product",(byte)1,0, subMenus));

        return ResultGenerator.genSuccessResult(menus);


    }

    private List<MenuDTO> transfer2Menus(List<SysPermission> permissions) {

        List<SysPermission> collect = permissions.stream().filter(p -> p.getPid() == 0).collect(Collectors.toList());

        List<MenuDTO> fistMenu = TransferUtils.poToDto(collect, MenuDTO.class);

        for (MenuDTO menuDTO : fistMenu){

            List<SysPermission> collect1 = permissions.stream().filter(p -> p.getPid() == menuDTO.getId()).collect(Collectors.toList());
            List<MenuDTO> subMenus = TransferUtils.poToDto(collect1, MenuDTO.class);
            menuDTO.setSubMenus(subMenus);
        }

        return fistMenu;
    }

    private Condition conditionConverter(SysPermissionQuery query) {

        Condition condition = new Condition(SysPermission.class);
        Example.Criteria criteria = condition.createCriteria();

        if(Objects.nonNull(query.getId())){
            criteria.andEqualTo("id",query.getId());
        }

        criteria.andEqualTo("status", StatusEnum.ON_LINE.status);

        if(Objects.nonNull(query.getIsParent())){
            criteria.andEqualTo("isParent",query.getIsParent());
        }

        if(Objects.nonNull(query.getPid())){
            criteria.andEqualTo("pid",query.getPid());
        }

        if(Objects.nonNull(query.getType())){
            criteria.andEqualTo("type",query.getType());
        }

        if(StringUtils.isNotEmpty(query.getName())){
            criteria.andLike("name","%"+query.getName()+"%");
        }

        if(StringUtils.isNotEmpty(query.getDescripion())){
            criteria.andLike("descripion","%"+query.getDescripion()+"%");
        }

        if(StringUtils.isNotEmpty(query.getUrl())){
            criteria.andLike("url","%"+query.getUrl()+"%");
        }


        QueryUtils.setSortCondition(condition,query.getSortby(),query.getOrdered());
        return condition;
    }
}
